/**
 * 
 */
package org.dragonfire.editor.syntax;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextViewer;

/**
 * @author Darth Android
 * @date Dec 27, 2007
 */
public class WordDoubleClickStrategy implements ITextDoubleClickStrategy {

	private String wordCharacters = "";

	public WordDoubleClickStrategy(String charactersRegex) {
		wordCharacters = charactersRegex;
	}

	public void doubleClicked(ITextViewer viewer) {
		selectWord(viewer, viewer.getSelectedRange().x);
	}

	public boolean selectWord(ITextViewer viewer, int caretPos) {
		IDocument doc = viewer.getDocument();
		int startPos = caretPos, endPos = startPos;
		if (caretPos < 0 || caretPos >= doc.getLength())
			return false;
		try {
			while (doc.get(startPos - 1, 1).matches(wordCharacters)) {
				startPos--;
				if (startPos < 0)
					break;
			}
			endPos = startPos;
			while (doc.get(endPos + 1, 1).matches(wordCharacters)) {
				endPos--;
				if (endPos >= doc.getLength())
					break;
			}
		} catch (BadLocationException ble) {
		}
		if (endPos - startPos > 0) {
			viewer.setSelectedRange(startPos, endPos);
			return true;
		}
		return false;
	}
}
